package quattrow;

import dblib.DB;
import dblib.NewConnectDialog;
import dblib.PDM;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;

public class QuattroW {

    public static void main(String[] args) {

        // Logger
        try {
            Logger.getLogger("").addHandler(new FileHandler("errorlog.xml"));
        } catch (IOException | SecurityException ex) {
            Logger.getLogger(QuattroW.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Look and feel
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(QuattroW.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Initialisation and Properties
        Vars.PropPath = System.getProperty("user.home") + "/.QuattroW";
        Vars.PropFileName = Vars.PropPath + "/Options.xml";
        File dir = new File(Vars.PropPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            Vars.setHostID(java.net.InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException ex) {
            Logger.getLogger(QuattroW.class.getName()).log(Level.SEVERE, null, ex);
        }

        Boolean NeedConnect = false;
        Vars.LoadProperties();

        if (!Vars.prop.containsKey("Username")) {
            //Vars.prop.setProperty("Username", "Username");
            NeedConnect = true;
        }
        if (!Vars.prop.containsKey("Userpass")) {
            //Vars.prop.setProperty("Userpass", "Userpass");
            NeedConnect = true;
        }
        if (!Vars.prop.containsKey("DB_URL")) {
            //Vars.prop.setProperty("DB_URL", "DB_URL");
            NeedConnect = true;
        }
        if (!Vars.prop.containsKey("LogW1")) {
            Vars.prop.setProperty("LogW1", "130");
        }
        if (!Vars.prop.containsKey("LogW2")) {
            Vars.prop.setProperty("LogW2", "120");
        }
        if (!Vars.prop.containsKey("LogW3")) {
            Vars.prop.setProperty("LogW3", "180");
        }
        if (!Vars.prop.containsKey("LogW4")) {
            Vars.prop.setProperty("LogW4", "570");
        }

        PDM pdm = new PDM();

        if (!NeedConnect) {
            pdm.addConnInstance("srv", Vars.prop.getProperty("Username"), Vars.prop.getProperty("Userpass"), Vars.prop.getProperty("DB_URL"));
            if (!PDM.isConnectionOk("srv")) {
                pdm.removeConnInstance("srv");
                NeedConnect = true;
            }
        }

        if (NeedConnect) {
            NewConnectDialog newConnDlg = new NewConnectDialog(null, true);

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `logs` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`hostid` VARCHAR(512) NOT NULL, "
                    + "`logtype` INT NOT NULL, "
                    + "`class` VARCHAR(4096) NOT NULL, "
                    + "`logtext` VARCHAR(4096) NOT NULL, "
                    + "`dt` DATETIME NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`)) ENGINE = InnoDB");

            newConnDlg.SetStrings(
                    "Для работы программы необходимо подключиться к серверу баз даных.",
                    "Все таблицы и настройки успешно созданы.");

            newConnDlg.setLocationRelativeTo(null);
            newConnDlg.setVisible(true);

            if (newConnDlg.getResult().equals("False")) {
                Runtime.getRuntime().exit(1);
            }

            Vars.prop.setProperty("Username", newConnDlg.getUsername());
            Vars.prop.setProperty("Userpass", newConnDlg.getPassword());
            Vars.prop.setProperty("DB_URL", newConnDlg.getURL());

            Vars.SaveProperties();
        }

        pdm.addConnInstance("srv",
                Vars.prop.getProperty("Username"),
                Vars.prop.getProperty("Userpass"),
                Vars.prop.getProperty("DB_URL"));
        pdm.addConnInstance("log",
                Vars.prop.getProperty("Username"),
                Vars.prop.getProperty("Userpass"),
                Vars.prop.getProperty("DB_URL"));

        // Run
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainFrame frm = new MainFrame();
                Logs.log(3, getClass().toString(), "Запуск программы");
                frm.setLocationRelativeTo(null);
                frm.setVisible(true);
            }
        });
    }
}
